<template>
  <div class="feedback">
    <!-- 顶部 -->
    <div class="feed-top flex between align-center">
      <div class="title">
        <h3>我要反馈</h3>
        <div>您的每个反馈，都将由我们的工作人员认真记录并解决</div>
      </div>
      <div class="rot flex align-center">
        <img src="../../assets/images/home/bot-icon.png" alt="" />
        <div class="cursor" @click="goRobot">机器人助手</div>
      </div>
    </div>
    <!-- /顶部 -->

    <!-- 对话 -->
    <div class="chat" ref="box">
      <div
        v-for="(item, index) in msgList"
        :key="index"
        class="content"
        :class="item.myself ? 'right' : 'left'"
      >
        <div class="init flex-row">
          <!-- 头像 -->
          <div class="user-photo">
            <img :src="item.photoSrc" />
          </div>
          <!-- /头像 -->

          <!-- 消息内容 -->
          <div class="user-text">
            <span
              v-show="item.myself"
              v-html="item.message"
              style="word-wrap: break-word; word-break: break-all"
            ></span>
            <div v-if="!item.myself" class="repeat flex-row">
              <div class="first-word" v-if="item.first">
                <div class="word-top">
                  <div class="time">下午好</div>
                  <div class="word-desc">
                    我们非常感谢您能提供反馈意见，我们将在收到您的问题后第一时间处理并及时给您回复。
                  </div>
                </div>

                <div class="list">
                  <span>猜你想反馈:</span>
                  <ul
                    class="flex"
                    :style="{ width: ulWidth, height: ulHeight }"
                  >
                    <li
                      class="flex bewteen"
                      style="margin-right: 10px"
                      v-for="(ite, idx) in item.list"
                      :key="idx"
                    >
                      <span class="list-index">{{ idx + 1 }}.</span>
                      <span class="list-item cursor" @click="pushInput(ite)">{{
                        ite.problem
                      }}</span>
                    </li>
                  </ul>
                </div>
              </div>

              <div class="other-word" v-else>
                <div
                  class="second-ques"
                  v-if="item.second"
                  v-html="item.secondQues"
                ></div>
                <div class="current" v-else-if="item.confm">
                  您的反馈为:“<span
                    style="
                      display: inline-block;
                      word-wrap: break-word;
                      word-break: break-all;
                      color: #0066ff;
                    "
                    >{{ item.msg }}</span
                  >”，若要修改问题可直接在对话框内输入，点此<span
                    class="cursor"
                    @click="confirmMsg"
                    style="color: red"
                    >确认</span
                  >问题
                </div>
                <div class="tel-ques" v-else-if="item.telQues">
                  <span style="color: #0066ff">请输入您的联系电话</span
                  >，以便我们后续与您联系
                </div>
                <div class="tel-current" v-else-if="item.telCurrent">
                  您的联系电话为:“<span style="color: #0066ff">{{
                    item.msg
                  }}</span
                  >”，若要修改联系电话请重新在对话框内输入您的电话，点此<span
                    class="cursor"
                    style="color: red"
                    @click="confirmTel(item.clickType, index)"
                    >确认</span
                  >联系电话
                </div>
                <div v-else>
                  <div>
                    我们已记录您的反馈:“<span style="color: #0066ff">{{
                      item.msg
                    }}</span
                    >”，我们将在三个工作日内审核并将回复发送到<span
                      style="color: #0066ff"
                      >本地宝微信公众号</span
                    >内，您还可以在<span style="color: #0066ff"
                      >反馈中心-反馈记录</span
                    >中查看处理进度，感谢您的反馈~祝您生活愉快~
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- /消息内容 -->
        </div>
        <div class="system flex align-center" v-if="item.overChat">
          <img src="../../assets/images/feedback/robot.png" alt="" /><span
            >对话已结束，若您还有其他反馈可继续在对话框内输入内容</span
          >
        </div>
        <div class="system flex align-center" v-if="item.sureTel">
          <img src="../../assets/images/feedback/tips.png" alt="" /><span
            >请先输入您的联系电话，再接入人工客服。</span
          >
        </div>
        <div class="system flex align-center" v-if="item.linkServe">
          <img src="../../assets/images/feedback/tips.png" alt="" /><span
            >本地宝人工客服已接入会话，我们预计三分钟内联系您。</span
          >
        </div>
      </div>

      
    </div>
    <!-- /对话 -->

    <!-- 输入框 -->
    <div class="bottom-input flex">
      <div class="rg-btn cursor" @click="clickKefu">人工客服</div>
      <!-- <el-input
        type="textarea"
        :rows="3"
        placeholder="请描述您的问题"
        v-model="inputValue"
        resize="none"
        class="input-box"
        @keydown="enter"
      >
      </el-input> -->
      <textarea
        class="input-box"
        v-model="inputValue"
        @keydown="enter"
        placeholder="请描述您的问题"
        style="color: #000"
      ></textarea>
      <div class="flex flex-end">
        <button @click="send">发送</button>
      </div>
    </div>
    <!-- /输入框 -->
  </div>
</template>

<script>
export default {
  name: "feedback",
  data() {
    return {
      currentTime: "",
      inputValue: "",
      msgList: [],
      overChat: false,
      titleList: [],
      category: "",
      getNews: 0,
      userQues: "",
      token: "",
      telNumber: "",
      url: "",
      cityname: "",
      ulWidth: "100%",
      ulHeight: "240px",
      linkServe: false,
    };
  },
  watch: {
    $route(to, from) {
      this.scrollBottom();
    },
  },
  created() {
    let refer = document.referrer;
    this.url = refer;
    this.$http
      .get(`?controller=fankui&action=getCityName&url=${this.url}`)
      .then((res) => {
        if (res.data.code === 0) {
          this.cityname = res.data.data.cityname;
        }
      });

    this.token = localStorage.getItem("token");

    this.getCategory();
  },
  methods: {
    getCategory() {
      this.$http
        .get(`?controller=fankui&action=getCategory&token=${this.token}`)
        .then((res) => {
          if (res.data.code === 0) {
            this.category = res.data.data;
            if (this.category.length > 12) {
              this.ulHeight = "400px";
            } else if (this.category.length > 20) {
              this.ulHeight = "520px";
            }
            this.msgList.push({
              first: true,
              myself: false,
              photoSrc: require("../../assets/images/feedback/robot.png"),
              list: this.category,
            });

            this.category.forEach((el) => {
              this.titleList.push(el.problem);
            });
            let nowTime = new Date().getTime();
            localStorage.setItem("startTime", nowTime);

            this.setCookies();
          } else if (res.data.code === -1) {
            this.$message(`${res.data.msg}`);
          } else if (res.data.code === -2) {
            localStorage.removeItem("token");
            this.$message.error(`token已过期,2秒后自动跳转到登录页`);
            setTimeout(() => {
              if (this.$route.query.cityname && this.$route.query.url) {
                let cityname = encodeURIComponent(this.$route.query.cityname);
                this.$router.replace(
                  `/login?cityname=${cityname}&url=${this.$route.query.url}`
                );
              } else {
                this.$router.replace(`/login`);
              }
            }, 2000);
          }
        });
    },

    /**
     * 保存cookie
     */
    setCookies() {
      let date = new Date();
      date.setSeconds(date.getSeconds() + 3600);
      document.cookie = `tokens=${
        this.token
      };Expires=${date.toUTCString()};path=/;domain=.bendibao.com;`;
    },
    /**
     * 点击询问
     *
     */
    pushInput(val) {
      this.inputValue = val.problem;

      if (this.inputValue !== "") {
        this.msgList.push({
          message: this.inputValue,
          myself: true,
          photoSrc: require("../../assets/images/feedback/self.png"),
        });
      }

      this.secondReq(val.id);
      this.inputValue = "";
    },

    /**
     * 二级回复接口
     *
     */
    secondReq(id) {
      this.$http
        .get(`?controller=fankui&action=getReply&id=${id}&token=${this.token}`)
        .then((res) => {
          if (res.data.code === 0) {
            let word2 = res.data.data.reply_content;
            let wordd = word2
              .replace("“", '“<span style="color: #0066FF">')
              .replace("”", "</span>”");
            this.msgList.push({
              message: this.inputValue,
              myself: false,
              photoSrc: require("../../assets/images/feedback/robot.png"),
              secondQues: wordd,
              second: true,
            });
            let nowTime = new Date().getTime();
            localStorage.setItem("startTime", nowTime);
            this.setCookies();
            this.scrollBottom();
          } else if (res.data.code === -1) {
            this.$message(`${res.data.msg}`);
          } else if (res.data.code === -2) {
            localStorage.removeItem("token");
            this.$message.error(`token已过期,2秒后自动跳转到登录页`);
            setTimeout(() => {
              if (this.$route.query.cityname && this.$route.query.url) {
                let cityname = encodeURIComponent(this.$route.query.cityname);
                this.$router.replace(
                  `/login?cityname=${cityname}&url=${this.$route.query.url}`
                );
              } else {
                this.$router.replace(`/login`);
              }
            }, 2000);
          }
        });
    },

    /**
     * 回车按钮事件
     *
     */
    enter(event) {
      if (event.keyCode == 13) {
        event.preventDefault(); // 阻止浏览器默认换行操作
        this.send(); // 发送文本
      }
    },

    /**
     * 点击发送
     *
     */
    send() {
      console.log(this.getNews);
      if (this.inputValue == "") {
        return;
      }

      if (this.inputValue == "人工客服" && this.getNews !== 3) {
        this.msgList.push({
          message: this.inputValue,
          myself: true,
          photoSrc: require("../../assets/images/feedback/self.png"),
          sureTel: true,
        });
        this.getNews = 2;
        this.inputValue = "";
        this.scrollBottom();
        return;
      }
      this.msgList.push({
        message: this.inputValue,
        myself: true,
        photoSrc: require("../../assets/images/feedback/self.png"),
      });
      if (this.getNews === 3) {
        this.getNews = 0
        console.log("正在发送到后台");
        this.inputValue = "";
        this.scrollBottom();
        return;
      }

      let index = this.titleList.indexOf(this.inputValue);
      if (index !== -1) {
        // 点击猜你想反馈
        this.secondReq(index + 1);
      } else {
        if (this.getNews === 0) {
          this.repeat();
          this.userQues = this.inputValue;
        } else if (this.getNews === 1) {
          this.telPhone(1);
        } else if (this.getNews === 2) {
          this.telPhone(2);
        }
      }
      this.inputValue = "";
      this.scrollBottom();
    },

    /**
     * 您的反馈为...
     *
     */
    repeat() {
      this.msgList.push({
        myself: false,
        photoSrc: require("../../assets/images/feedback/robot.png"),
        msg: this.inputValue,
        confm: true,
      });
    },
    /**
     * 你的联系电话为
     *
     */
    telPhone(num) {
      if (num == 1) {
        // 普通反馈
        this.msgList.push({
          myself: false,
          photoSrc: require("../../assets/images/feedback/robot.png"),
          msg: this.inputValue,
          telCurrent: true,
          clickType: num,
        });
      } else {
        // 人工 
        this.msgList.push({
          myself: false,
          photoSrc: require("../../assets/images/feedback/robot.png"),
          msg: this.inputValue,
          telCurrent: true,
          clickType: num,
          linkServe: false,
        });
      }

      this.telNumber = this.inputValue;
    },

    /**
     * 确认信息事件
     *
     */
    confirmMsg() {
      console.log("反馈内容", this.inputValue);
      this.msgList.push({
        myself: false,
        photoSrc: require("../../assets/images/feedback/robot.png"),
        msg: this.inputValue,
        telQues: true,
      });

      this.getNews = 1;
      this.scrollBottom();
    },

    /**
     * 确认电话事件
     *
     */
    confirmTel(type, index) {
      console.log("dainhua", this.telNumber);
      if (type === 1) {
        // 普通反馈的确认电话
        console.log(555);
        this.getNews = 0;
        this.overChat = true;
        let nowTime = new Date().getTime();
        localStorage.setItem("startTime", nowTime);
        this.setCookies();
        this.scrollBottom();
        return;
        let data = {
          cityname: this.cityname,
          url: this.url,
          feed_content: this.userQues,
          tel: this.telNumber,
          token: this.token,
        };
        this.$http
          .post(`?controller=fankui&action=saveFeedContent`, data)
          .then((res) => {
            if (res.data.code === 0) {
              this.msgList.push({
                myself: false,
                photoSrc: require("../../assets/images/feedback/robot.png"),
                msg: this.userQues,
                overChat: true,
              });
              this.getNews = 0;
              this.overChat = true;
              let nowTime = new Date().getTime();
              localStorage.setItem("startTime", nowTime);
              this.setCookies();
              this.scrollBottom();
            } else if (res.data.code === -1) {
              this.$message(`${res.data.msg}`);
            } else if (res.data.code === -2) {
              localStorage.removeItem("token");
              this.$message.error(`token已过期,2秒后自动跳转到登录页`);
              setTimeout(() => {
                if (this.$route.query.cityname && this.$route.query.url) {
                  let cityname = encodeURIComponent(this.$route.query.cityname);
                  this.$router.replace(
                    `/login?cityname=${cityname}&url=${this.$route.query.url}`
                  );
                } else {
                  this.$router.replace(`/login`);
                }
              }, 2000);
            }
          });
      } else {
        // 人工客服的确认电话
        this.msgList[index].linkServe = true;
        this.getNews = 3;
      }
      this.scrollBottom();
      this.connectKefu();
    },

    /**
     * 消息自动滚动到底部
     *
     */
    scrollBottom() {
      this.$nextTick(() => {
        let ele = this.$refs.box;
        ele.scrollTop = ele.scrollHeight;
      });
    },

    goRobot() {
      this.$http.get(`?controller=fankui&action=getGzhInfo`).then((res) => {
        if (res.data.code === 0) {
          let city = [];
          res.data.data.forEach((val) => {
            if (
              val.gzh_name.indexOf(this.cityname) !== -1 &&
              this.cityname !== ""
            ) {
              city.push(val);
            }
          });
          if (city.length !== 0) {
            window.open(
              `http://robot.bendibao.com/?citycode=${city[0].citycode}&gzh=${city[0].gzh_account}`
            );
          } else {
            window.open(`http://u.bendibao.com/fankui/index.html#/city`);
          }
        }
      });
    },

    /**
     * 客服按钮点击事件
    */
    clickKefu(){
      this.inputValue = "人工客服";
      this.send()
    },

    /**
     * 连接websocket
     * */ 
    connectKefu() {
      console.log("连接中");
    },
  },

  updated() {},
};
</script>

<style scoped lang="less">
@import "./feedback.less";
</style>
